#coding=utf-8
'''
Created on 2017-06-13

@author: sandy
'''

import Manager
import logging
import ManagerBuild

class RemoteManager(object):

    def __init__(self):
        self.sid = 0
        self.msip = u''
        self.msport = 0
        self.startfunc = None
        self.startparam = None
        self.cfgcallback = []
        self.configlist = []
        self.started = False

    def init(self,sid,msip,msport,logfile,loglevel):
        self.sid = sid
        self.msip = msip
        self.msport = msport
        self.logfile = logfile
        self.loglevel = loglevel

    def start(self, startfunc, *param):
        self.startfunc = startfunc
        self.startparam = param
        self.addConfigCallback(self)
        Manager.instance.start(self.msip, self.msport)

    def stop(self):
        pass

    def getConfigList(self):
        return self.configlist

    def onLoginRet(self):
        if self.started == False:
            self.started = True
            if self.startfunc:
                self.startfunc(*self.startparam) 

    def recvConfFin(self):
        if self.startfunc:
            self.startfunc(*self.startparam) 

    def addConfigCallback(self,cb):
        self.cfgcallback.append(cb)

    def removeConfigCallback(self,cb):
        self.cfgcallback.remove(cb)

    def requestConfig(self, cfglist,startfunc, *param):
        self.startfunc = startfunc
        self.startparam = param
        logging.debug(u'requestConfig %s',cfglist)
        for cfgname in cfglist:
            Manager.instance.sendPacket(ManagerBuild.getConfig(cfgname))
        else:
            Manager.instance.sendPacket(ManagerBuild.getConfigEnd())

    def onGotCfg(self,cfgname, jf):
        for cb in self.cfgcallback:
            try:
                cb.onRemoteConfig(cfgname, jf)
            except Exception:
                logging.exception(u'cb.onRemoteConfig() cfgname=%s', cfgname)

    def onRemoteConfig(self, cfgname, jf):
        ctype,cname = cfgname.split(u".")
        if ctype==u'server'+unicode(self.sid) and cname==u'otherconfig':
            self.configlist = jf

instance = RemoteManager()
